package com.cjq.controller;

import com.cjq.domain.User;
import com.cjq.service.UserService;
import com.cjq.utils.Result;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.LinkedList;
import java.util.List;

/**
 * @author junqiancai@foxmail.com
 * @since 2021/6/16 21:23
 */
@RestController
public class AccountController {
    @Value("${diy.props.init-password}")
    private String initPassword;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private UserService userService;

    @PreAuthorize("hasAnyRole('ADMIN','SUPER')")
    @PostMapping("/upload/account")
    Result uploadAccountFile(@RequestParam("file") MultipartFile file,HttpServletRequest request) throws IOException {
        request.setCharacterEncoding("UTF-8");
        if(file==null) throw new IOException("file数据为null");
        InputStreamReader reader = new InputStreamReader(file.getInputStream(), StandardCharsets.UTF_8);
        List<User> userList = new LinkedList<>();//保存每一行
        CSVParser csvParser = CSVFormat.DEFAULT.withFirstRecordAsHeader().parse(reader);
        List<String> headers = csvParser.getHeaderNames();  //获取表头
        List<CSVRecord> records = csvParser.getRecords();
        records.forEach(record->{
            final User user = new User();
            headers.forEach(it->{
                String val = record.get(it);
                switch (it){
                    case "username":user.setUsername(val);break;
                    case "userType":user.setUserType(Integer.valueOf(val));break;
                    case "realName":user.setRealName(val);break;
                    case "phone":user.setPhone(val);break;
                    case "school":user.setSchool(val);break;
                    case "department":user.setDepartment(val);break;
                    case "grade":user.setGrade(Integer.valueOf(val));break;
                    case "major":user.setMajor(val);break;
                    case "className":user.setClassName(val);break;
                }
            });
            user.setPassword(passwordEncoder.encode(initPassword)).setEnablePassword(1).setRoleId(2);
            userList.add(user);
        });
        userService.saveBatch(userList);
        return Result.succeed(Result.SUCCESS,"添加成功");
    }
}
